//
//  VideoVC.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/4/24.
//

import Foundation
import UIKit
import Kingfisher
import AVKit

class VideoVC: SubLevelViewController {
    private var playerCtl: AVPlayerViewController?
    var playerItem: AVPlayerItem?
    var player: AVPlayer?
    
    var urlStr: String = "" {
        didSet {
            setupPlayer()
        }
    }
    
    // MARK: - Override
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "查看视频"
        
        setupPlayer()
    }
    
    func setupPlayer() {
        if playerCtl?.view.superview != nil {
            playerCtl?.view.removeFromSuperview()
            playerCtl = nil
        }
        
        playerItem = AVPlayerItem(url: URL(fileURLWithPath: urlStr))
        playerCtl = AVPlayerViewController()
        if let plCtrl = playerCtl {
            plCtrl.delegate = self
            plCtrl.player = AVPlayer(playerItem: playerItem)
            plCtrl.videoGravity = .resizeAspect
            plCtrl.showsPlaybackControls = false
            plCtrl.player?.volume = 1.0
            player = plCtrl.player
            view.addSubview(plCtrl.view)
            plCtrl.view.snp.remakeConstraints({ make in
                make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
                make.left.right.equalToSuperview()
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            })
        }
    }
}

extension VideoVC: AVPlayerViewControllerDelegate {
    func playerViewController(_ playerViewController: AVPlayerViewController, willBeginFullScreenPresentationWithAnimationCoordinator coordinator: UIViewControllerTransitionCoordinator) {}
    
    func playerViewController(_ playerViewController: AVPlayerViewController, willEndFullScreenPresentationWithAnimationCoordinator coordinator: UIViewControllerTransitionCoordinator) {}
}
